package cn.donave.framework.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class CookieHelper {
	private CookieHelper() {
	}

	public static final Cookie getCookie(HttpServletRequest request,
			String cookieName) {
		if (cookieName == null || cookieName.length() <= 0)
			return null;
		Cookie cookies[] = request.getCookies();
		if (cookies == null || cookies.length <= 0)
			return null;
		Cookie cookie = null;
		for (int i = 0; i < cookies.length; i++) {
			if (!cookieName.equals(cookies[i].getName()))
				continue;
			cookie = cookies[i];
			if (request.getServerName().equals(cookie.getDomain()))
				break;
		}
		return cookie;
	}

	public static final void setCookie(HttpServletResponse response,
			String cookieName, String cookieValue, int maxAge) {
		if (cookieValue == null)
			cookieValue = "";
		Cookie cookie = new Cookie(cookieName, cookieValue);
		cookie.setMaxAge(maxAge);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

}
